#include "conv_pif.hpp"
// #define PY_ARRAY_UNIQUE_SYMBOL myextn_ARRAY_API
// #define NO_IMPORT_ARRAY
// #include <numpy/arrayobject.h>

// See http://shitohichiumaya.blogspot.in/2012/01/passing-user-defined-python-object-to-c_4561.html

// See http://thread.gmane.org/gmane.comp.python.numeric.general/47273/

//Convert (Python) Numpy int to (C++) int.

// int pynumpy2cppint(PyObject* obj)
// {
//   boost::python::object bpo(boost::python::handle<>(boost::python::borrowed(obj)));
//   return extract<int>(bpo.attr("__int__")());
// }

string pyunicode2cppstring(PyObject* obj)
{
  // npy_int64 val;
  // PyArray_ScalarAsCtype(obj, &val);
  // return val;
  return extract<string>(PyUnicode_AsASCIIString(obj));
}

struct cppstring_from_python_unicode
{
  cppstring_from_python_unicode()
  {
    boost::python::converter::registry::push_back(
						  &convertible,
						  &construct,
						  boost::python::type_id<string>());
  }

  static void* convertible(PyObject* obj_ptr)
  {
    // If type is not a unicode object, then exit.
    //if(!PyObject_TypeCheck(obj_ptr, &PyInt32ArrType_Type) && !PyObject_TypeCheck(obj_ptr, &PyInt64ArrType_Type)) return 0;
    if(!PyUnicode_Check(obj_ptr)) return 0;
    return obj_ptr;
  }

  static void construct(
			PyObject* obj_ptr,
			boost::python::converter::rvalue_from_python_stage1_data* data)
  {
    void* storage = (
		     (boost::python::converter::rvalue_from_python_storage<string>*)
		     data)->storage.bytes;
    new (storage) string(pyunicode2cppstring(obj_ptr));
    data->convertible = storage;
  }
};

void export_cppunicode_conv()
{
  cppstring_from_python_unicode();
}
